import React, { useState, useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { NavItem } from "./types";
import "./App.css";
import { useAuthStore } from "./zus";
import service from './utils/axios';

const TABS_STORAGE_KEY = "active_tabs";

const App: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState<boolean>(false);
  const [activeTabs, setActiveTabs] = useState<NavItem[]>([]);
  let { menu } = useAuthStore();
  // Navigation menu items - 已更新为新的导航项
  let allowpath = menu.map((i) => ({
    path: i.path,
    name: i.title,
    icon: i.icon,
  }));
  let [time,settime]=useState("1997-07-01 00:00:00")
  // console.log("menu", menu);

  // const allpath=[
  //   { path: '/authority', name: '权限', icon: '🔑' },
  //   { path: '/overview', name: '统计', icon: '📊' },
  //   { path: '/products', name: '商品', icon: '🛒' },
  //   { path: '/ads', name: '广告', icon: '📢' },
  //   { path: '/users', name: '用户', icon: '👥' },
  //   { path: '/orders', name: '订单', icon: '📝' },
  //   { path: '/operations', name: '运营', icon: '⚙️' },
  // ]
  let navItems: NavItem[] = [...allowpath];

  // 初始化时从Session Storage加载标签
  useEffect(() => {
    if (!menu.length) return;
    const storedTabs = sessionStorage.getItem(TABS_STORAGE_KEY);
    if (storedTabs) {
      try {
        const parsedTabs = JSON.parse(storedTabs);
        const filteredTabs = parsedTabs.filter(
          (tab: NavItem) => navItems.some((menu) => menu.path === tab.path)
        );
        setActiveTabs(filteredTabs);
      } catch (e) {
        console.error("Failed to parse stored tabs:", e);
      }
    }
  }, [menu]);

  // 监听路由变化，更新标签
  useEffect(() => {
    if (location.pathname === "/") return;

    const currentNavItem = navItems.find(
      (item) => item.path === location.pathname
    );
    if (currentNavItem) {
      // 检查标签是否已经存在
      if (!activeTabs.some((tab) => tab.path === currentNavItem.path)) {
        // 确保不会添加重复的标签
        setActiveTabs((prev) => {
          // 过滤掉任何可能已经存在的相同路径的标签
          const filteredTabs = prev.filter(
            (tab) => tab.path !== currentNavItem.path
          );
          // 然后添加新标签
          const newTabs = [...filteredTabs, currentNavItem];
          // 保存到Session Storage
          sessionStorage.setItem(TABS_STORAGE_KEY, JSON.stringify(newTabs));
          return newTabs;
        });
      }
    }
  }, [location.pathname, navItems]);

  

  // 处理关闭标签
  const handleCloseTab = (event: React.MouseEvent, path: string) => {
    event.stopPropagation();
    
    const newTabs = activeTabs.filter(tab => tab.path !== path);
    setActiveTabs(newTabs);
    
    // 保存更新后的标签到Session Storage
    sessionStorage.setItem(TABS_STORAGE_KEY, JSON.stringify(newTabs));
    
    // 如果关闭的是当前活动标签，导航到最后一个标签或首页
    if (location.pathname === path) {
      if (newTabs.length > 0) {
        navigate(newTabs[newTabs.length - 1].path);
      } else {
        navigate('/');
      }
    }
  };
  

  // 处理左侧菜单点击，添加标签
  const handleNavItemClick = (navItem: NavItem) => {
    // 检查标签是否已经存在
    if (!activeTabs.some(tab => tab.path === navItem.path)) {
      const newTabs = [...activeTabs, navItem];
      setActiveTabs(newTabs);
      // 保存到Session Storage
      sessionStorage.setItem(TABS_STORAGE_KEY, JSON.stringify(newTabs));
    }
    navigate(navItem.path);
  };

  const nologin=async()=>{
    await service.post('/WYQ/nologin',{lastLogin:new Date(),name:localStorage.getItem('name')})
    localStorage.removeItem('name')
    localStorage.removeItem('token')
    navigate('/login')
  }
  const gettime=async()=>{
    let res=await service.get('/WYQ/time',{params:{name:localStorage.getItem('name')}})
    console.log(res);
    settime(res.time)
  }
  useEffect(()=>{
    gettime()
  },[])
  return (
    <div className="app-container">
      {/* Left sidebar navigation */}
      <div className={`sidebar ${collapsed ? 'collapsed' : ''}`}>
        <nav className="nav-menu">
          {navItems.map((item) => (
            <div 
              key={item.path} 
              className={`nav-item ${location.pathname === item.path ? 'active' : ''}`}
              onClick={() => handleNavItemClick(item)}
            >
              <span className="nav-icon">{item.icon}</span>
              {!collapsed && <span className="nav-text">{item.name}</span>}
            </div>
          ))}
        </nav>
        <button 
          className="collapse-btn" 
          onClick={() => setCollapsed(!collapsed)}
        >
          {collapsed ? '>' : '<'}
        </button>
      </div>
      
      {/* Right content area */}
      <div className="content-container">
        <div className="breadcrumb-container">
          <div>
          {activeTabs.map((tab) => (
            <div 
              key={tab.path}
              className={`tab-item ${location.pathname === tab.path ? 'active' : ''}`}
              onClick={() => navigate(tab.path)}
            >
              <span>{tab.name}</span>
              <button 
                className="close-tab" 
                onClick={(e) => handleCloseTab(e, tab.path)}
              >
                ×
              </button>
            </div>
          ))}
          </div>
          <div className="user-info">
            <span className="last-login">上次登录时间: {new Date(time).toLocaleString()}</span>
            <span className="user-avatar" onClick={nologin}>你好{localStorage.getItem('name')} 退出登录</span>
          </div>
        </div>
        
        {/* Main content */}
        <div className="main-content">
          <Outlet />
        </div>
      </div>
    </div>
  );
};

export default App; 
